package com.leyou.gateway.filter;

import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.constant.LyConstants;
import com.leyou.gateway.config.FilterProperties;
import com.leyou.gateway.config.JwtProperties;
import com.leyou.gateway.task.TokenHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private JwtProperties jwtProp;

    @Autowired
    private FilterProperties filterProp;

    @Autowired
    private TokenHolder tokenHolder;

    /**
     * 自定义网关过滤器
     * @param exchange 上下问对象 request, response
     * @param chain 过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取request域
        ServerHttpRequest request = exchange.getRequest();
        //获取response域
        ServerHttpResponse response = exchange.getResponse();
        //对所有请求添加请求头
        request.mutate().header(LyConstants.APP_TOKEN_HEADER, tokenHolder.getToken()).build();
        //获取当前请求地址
        String url = request.getURI().getPath();
        //通过url路径判断当前请求地址是否需要登录，如果在白名单，就不需要登录
        if(isWhite(url)){
            //继续访问其他过滤器和微服务
            return chain.filter(exchange);
        }
        //获取cookie中的token，getFirst方法是表示通过cookie名称获取cookie
        String token = request.getCookies().getFirst(jwtProp.getCookie().getCookieName()).getValue();
        //解析token
        Payload<UserInfo> payload = null;
        try {
            payload = JwtUtils.getInfoFromToken(token, jwtProp.getPublicKey(), UserInfo.class);
        }catch (Exception e){
            //表示需要登录，但是token却不合法，这里，直接终止当前请求，不允许继续访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //获取当前用户的id
        Long userId = payload.getUserInfo().getId();
        //将用户id放入下一次请求的请求头中
        request.mutate().header(LyConstants.USER_HOLDER_KEY, userId.toString()).build();
        //表示请求是合法的，继续访问其他过滤器和微服务
        return chain.filter(exchange);
    }

    private boolean isWhite(String url) {
        for (String allowPath : filterProp.getAllowPaths()) {
            if(url.startsWith(allowPath)){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }

}
